// OneWayFlightSearch.vue - 单程航班搜索组件
<template>
  <div class="oneway-flight-search">
    <!-- 搜索表单 -->
    <el-card class="search-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span class="card-title">🛫 单程机票搜索</span>
          <div class="header-actions">
            <el-button
                type="primary"
                size="small"
                @click="showScheduleDialog = true"
                :icon="Timer">
              定时任务
            </el-button>
          </div>
        </div>
      </template>

      <el-form
          ref="searchFormRef"
          :model="searchForm"
          :rules="searchRules"
          label-width="100px">

        <!-- 出发地和目的地 -->
        <el-row :gutter="20">
          <el-col :span="10">
            <el-form-item label="出发地" prop="departure">
              <el-select
                  v-model="searchForm.departure"
                  placeholder="选择出发地"
                  filterable
                  style="width: 100%">
                <el-option
                    v-for="airport in airports"
                    :key="airport.value"
                    :label="airport.label"
                    :value="airport.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="2" style="text-align: center; line-height: 40px;">
            <el-button
                type="primary"
                :icon="RefreshRight"
                @click="swapLocations"
                circle>
            </el-button>
          </el-col>
          <el-col :span="10">
            <el-form-item label="目的地" prop="destination">
              <el-select
                  v-model="searchForm.destination"
                  placeholder="选择目的地"
                  filterable
                  style="width: 100%">
                <el-option
                    v-for="airport in airports"
                    :key="airport.value"
                    :label="airport.label"
                    :value="airport.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 日期和乘客数量 -->
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="出发日期" prop="departDate">
              <el-date-picker
                  v-model="searchForm.departDate"
                  type="date"
                  placeholder="选择出发日期"
                  :disabled-date="disabledDepartDate"
                  style="width: 100%"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="过滤日期" prop="orderDate">
              <el-date-picker
                  v-model="searchForm.orderDate"
                  type="datetime"
                  placeholder="选择出发日期"
                  :disabled-date="disabledOrderDate"
                  style="width: 100%"
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="成人" prop="adults">
              <el-input-number
                  v-model="searchForm.adults"
                  :min="1"
                  :max="9"
                  style="width: 100%">
              </el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="儿童">
              <el-input-number
                  v-model="searchForm.children"
                  :min="0"
                  :max="9"
                  style="width: 100%">
              </el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="婴儿">
              <el-input-number
                  v-model="searchForm.infants"
                  :min="0"
                  :max="9"
                  style="width: 100%">
              </el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="是否直飞">
              <el-checkbox
                  v-model="searchForm.directFlight">
              </el-checkbox>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 操作按钮 -->
        <el-form-item>
          <el-button
              type="primary"
              @click="searchFlights"
              :loading="searching"
              :icon="Search"
              size="large">
            {{ searching ? '搜索中...' : '搜索机票' }}
          </el-button>
          <el-button
              type="success"
              @click="showExportDialog = true"
              :loading="exporting"
              :icon="Download"
              size="large"
              :disabled="!hasResults">
            导出Excel
          </el-button>
          <el-button @click="resetForm" size="large" :icon="RefreshLeft">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 搜索结果 -->
    <el-card v-if="hasResults" class="result-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span class="card-title">搜索结果</span>
          <div class="result-summary">
            <el-tag type="success" effect="light">
              找到 {{ filteredFlights.length }} 个航班
              <span v-if="filteredFlights.length !== searchResult.totalCount">
                (共 {{ searchResult.totalCount }} 个)
              </span>
            </el-tag>
            <el-tag type="info" effect="light">TransactionID: {{ searchResult.transactionId }}</el-tag>
          </div>
        </div>
      </template>

      <!-- 筛选控制栏 -->
      <div class="filter-controls">
        <el-row :gutter="20" align="middle">
          <el-col :span="6">
            <div class="control-group">
              <span class="control-label">航班类型：</span>
              <el-select v-model="flightTypeFilter" size="small" style="width: 120px;" @change="onFilterChange">
                <el-option label="全部" value="all"></el-option>
                <el-option label="仅直飞" value="direct"></el-option>
                <el-option label="仅中转" value="transfer"></el-option>
              </el-select>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="control-group">
              <span class="control-label">排序：</span>
              <el-select v-model="sortMode" size="small" style="width: 120px;" @change="onFilterChange">
                <el-option label="价格升序" value="price_asc"></el-option>
                <el-option label="价格降序" value="price_desc"></el-option>
                <el-option label="直飞优先" value="direct_first"></el-option>
              </el-select>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="filter-stats">
              <el-tag size="small" type="primary">
                直飞: {{ getDirectFlightCount() }}
              </el-tag>
              <el-tag size="small" type="warning" style="margin-left: 8px;">
                中转: {{ getTransferFlightCount() }}
              </el-tag>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="control-group">
              <span class="control-label">每页显示：</span>
              <el-select v-model="pagination.pageSize" size="small" style="width: 80px;" @change="onPageSizeChange">
                <el-option label="20" :value="20"></el-option>
                <el-option label="50" :value="50"></el-option>
                <el-option label="100" :value="100"></el-option>
                <el-option label="全部" :value="0"></el-option>
              </el-select>
            </div>
          </el-col>
        </el-row>
      </div>

      <!-- 分页控制 -->
      <div class="pagination-controls">
        <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[20, 50, 100]"
            :total="filteredFlights.length"
            :background="true"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="onPageSizeChange"
            @current-change="onPageChange">
        </el-pagination>
      </div>

      <!-- 航班表格 -->
      <el-table
          :data="currentPageFlights"
          stripe
          style="width: 100%"
          class="flight-table"
          v-loading="tableLoading"
          row-key="getRowKey">

        <el-table-column prop="flightNumber" label="航班号" width="140" show-overflow-tooltip>
          <template #default="{ row }">
            <div class="flight-number-cell">
              <span class="flight-no">{{ row.flightNumber }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="航程" width="220">
          <template #default="{ row }">
            <div class="flight-time">
              <div class="time-range">{{ formatTime(row.departureTime) }} - {{ formatTime(row.arrivalTime) }}</div>
              <div class="duration">{{ row.duration }}</div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="机场" width="280">
          <template #default="{ row }">
            <div class="airport-info">
              <div class="airport-item">
                <el-tag size="small" effect="plain">{{ row.departureAirport || getAirportName(row.departureAirportCode) }}</el-tag>
                <span class="city-name">{{ row.departureCity || getCityName(row.departureCityCode) }}</span>
              </div>
              <el-icon class="route-arrow"><Right /></el-icon>
              <div class="airport-item">
                <el-tag size="small" effect="plain">{{ row.arrivalAirport || getAirportName(row.arrivalAirportCode) }}</el-tag>
                <span class="city-name">{{ row.arrivalCity || getCityName(row.arrivalCityCode) }}</span>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="中转" width="100">
          <template #default="{ row }">
            <el-tag v-if="row.transferCount === 0" type="success" size="small">直飞</el-tag>
            <el-tag v-else type="warning" size="small" @click="showTransferDetails(row)">
              {{ row.transferCount }}转
              <el-icon><InfoFilled /></el-icon>
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="价格" width="150" sortable>
          <template #default="{ row }">
            <div class="price-cell">
              <div class="price-display">
                <span class="currency">{{ row.currency }}</span>
                <span class="amount">{{ row.adultTotalPrice }}</span>
              </div>
              <div class="price-breakdown">
                基础: {{ row.adultPrice }} + 税: {{ row.adultTax }}
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="cabinClass" label="舱位" width="80">
          <template #default="{ row }">
            <el-tag size="small" :type="getCabinType(row.cabinClass)">
              {{ getCabinLabel(row.cabinClass) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button size="small" type="primary" text @click="viewFlightDetail(row)">
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 底部分页 -->
      <div class="pagination-controls bottom-pagination">
        <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[20, 50, 100]"
            :total="filteredFlights.length"
            :background="true"
            layout="total, prev, pager, next"
            @size-change="onPageSizeChange"
            @current-change="onPageChange">
        </el-pagination>
      </div>
    </el-card>

    <!-- 中转详情对话框 -->
    <el-dialog
        v-model="showTransferDialog"
        title="中转航班详情"
        width="70%"
        destroy-on-close>
      <OneWayFlightDetail v-if="selectedTransferFlight" :flight="selectedTransferFlight" />
    </el-dialog>

    <!-- 航班详情对话框 -->
    <el-dialog
        v-model="showFlightDetailDialog"
        title="航班详情"
        width="60%"
        destroy-on-close>
      <OneWayFlightDetail v-if="selectedFlight" :flight="selectedFlight" />
    </el-dialog>

    <!-- 导出对话框 -->
    <el-dialog
        v-model="showExportDialog"
        title="导出设置"
        width="600px"
        destroy-on-close>
      <OneWayExportDialog
          :flights="filteredFlights"
          :search-request="searchForm"
          @export="handleExport"
          @close="showExportDialog = false" />
    </el-dialog>

    <!-- 定时任务对话框 -->
    <el-dialog
        v-model="showScheduleDialog"
        title="定时任务管理"
        width="80%"
        top="5vh"
        destroy-on-close>
      <ScheduleTaskManager
          :search-form="{ ...searchForm, tripType: 'oneway' }"
          @task-created="onTaskCreated" />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch, onMounted, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  Search,
  Download,
  Timer,
  RefreshRight,
  RefreshLeft,
  Right,
  InfoFilled
} from '@element-plus/icons-vue'
import OneWayFlightDetail from './OneWayFlightDetail.vue'
import OneWayExportDialog from './OneWayExportDialog.vue'
import ScheduleTaskManager from '../views/ScheduleTaskManager.vue'
import oneWayFlightApi from '@/api/oneWayFlight'
import { validateSearchForm } from '@/utils/helpers'
import airlineNames from "@/utils/airlineNames.js"
import airportNames from "@/utils/airportNames.js"
import cityNames from "@/utils/cityNames.js"
import airports from "@/utils/airports.js"

// 路由
const route = useRoute()
const router = useRouter()

// 响应式数据
const searchFormRef = ref()
const showScheduleDialog = ref(false)
const showFlightDetailDialog = ref(false)
const showExportDialog = ref(false)
const showTransferDialog = ref(false)
const searching = ref(false)
const exporting = ref(false)
const tableLoading = ref(false)
const selectedFlight = ref(null)
const selectedTransferFlight = ref(null)

// 筛选和控制
const flightTypeFilter = ref('all')
const sortMode = ref('direct_first')

// 分页控制
const pagination = reactive({
  currentPage: 1,
  pageSize: 50,
  total: 0
})

// 搜索表单
const searchForm = reactive({
  departure: '',
  destination: '',
  departDate: '',
  orderDate: '',
  adults: 1,
  children: 1,
  infants: 1,
  directFlight: true
})

// 搜索结果
const searchResult = reactive({
  flights: [],
  totalCount: 0,
  transactionId: '',
  success: false
})

// 验证规则
const searchRules = {
  departure: [
    { required: true, message: '请选择出发地', trigger: 'change' }
  ],
  destination: [
    { required: true, message: '请选择目的地', trigger: 'change' }
  ],
  departDate: [
    { required: true, message: '请选择出发日期', trigger: 'change' }
  ]
}

// 计算属性
const hasResults = computed(() => {
  return searchResult.flights && searchResult.flights.length > 0
})

const filteredFlights = computed(() => {
  if (!searchResult.flights || searchResult.flights.length === 0) {
    return []
  }

  let flights = searchResult.flights.slice()

  // 应用筛选条件
  if (flightTypeFilter.value === 'direct') {
    flights = flights.filter(flight => flight.transferCount === 0)
  } else if (flightTypeFilter.value === 'transfer') {
    flights = flights.filter(flight => flight.transferCount > 0)
  }

  // 应用排序
  if (sortMode.value === 'price_asc') {
    flights.sort((a, b) => a.adultTotalPrice - b.adultTotalPrice)
  } else if (sortMode.value === 'price_desc') {
    flights.sort((a, b) => b.adultTotalPrice - a.adultTotalPrice)
  } else if (sortMode.value === 'direct_first') {
    flights.sort((a, b) => {
      if (a.transferCount === 0 && b.transferCount > 0) return -1
      if (a.transferCount > 0 && b.transferCount === 0) return 1
      return a.adultTotalPrice - b.adultTotalPrice
    })
  }

  pagination.total = flights.length
  return flights
})

const currentPageFlights = computed(() => {
  if (!shouldShowPagination.value || pagination.pageSize === 0) {
    return filteredFlights.value
  }

  const start = (pagination.currentPage - 1) * pagination.pageSize
  const end = start + pagination.pageSize
  return filteredFlights.value.slice(start, end)
})

const shouldShowPagination = computed(() => {
  return filteredFlights.value.length > 20 && pagination.pageSize > 0
})

const disabledDepartDate = (time) => {
  return time.getTime() < Date.now() - 8.64e7
}

const disabledOrderDate = (time) => {
  return time.getTime() < Date.now() - 8.64e7
}

// 方法
const searchFlights = async () => {
  if (!searchFormRef.value) return

  try {
    await searchFormRef.value.validate()

    const errors = validateSearchForm({ ...searchForm, tripType: 'oneway' })
    if (errors.length > 0) {
      ElMessage.error(errors[0])
      return
    }

    searching.value = true

    const response = await oneWayFlightApi.searchOneWayFlights({
      ...searchForm,
      tripType: 'oneway'
    })

    if (response.success) {

      Object.assign(searchResult, response.data)
      pagination.currentPage = 1
      pagination.total = response.data.totalCount
      ElMessage.success(`搜索完成，找到 ${response.data.totalCount} 个航班`)
    } else {
      ElMessage.error(response.message || '搜索失败')
    }
  } catch (error) {
    console.error('搜索失败:', error)
    ElMessage.error('搜索失败，请稍后重试')
  } finally {
    searching.value = false
  }
}

const getDirectFlightCount = () => {
  return filteredFlights.value.filter(flight => flight.transferCount === 0).length
}

const getTransferFlightCount = () => {
  return filteredFlights.value.filter(flight => flight.transferCount > 0).length
}

const swapLocations = () => {
  const temp = searchForm.departure
  searchForm.departure = searchForm.destination
  searchForm.destination = temp
}

const resetForm = () => {
  searchFormRef.value?.resetFields()
  Object.assign(searchResult, {
    flights: [],
    totalCount: 0,
    transactionId: '',
    success: false
  })
  flightTypeFilter.value = 'all'
  sortMode.value = 'direct_first'
  pagination.currentPage = 1
  pagination.pageSize = 50
}

const onFilterChange = () => {
  pagination.currentPage = 1
}

const onPageSizeChange = (size) => {
  pagination.pageSize = size
  pagination.currentPage = 1
}

const onPageChange = (page) => {
  pagination.currentPage = page
}

const formatTime = (dateTimeStr) => {
  if (!dateTimeStr) return ''
  try {
    return dateTimeStr.substring(11, 16)
  } catch (e) {
    return dateTimeStr
  }
}

const getAirportName = (airportCode) => {
  return airportNames[airportCode] || airportCode
}

const getCityName = (cityCode) => {
  return cityNames[cityCode] || cityCode
}

const getCabinType = (cabinClass) => {
  const typeMap = {
    'Y': 'success',
    'Y_S': 'success',
    'C': 'warning',
    'C_S': 'warning',
    'F': 'danger',
    'F_S': 'danger'
  }
  return typeMap[cabinClass] || 'info'
}

const getCabinLabel = (cabinClass) => {
  const labelMap = {
    'Y': '经济舱',
    'Y_S': '经济舱',
    'C': '商务舱',
    'C_S': '商务舱',
    'F': '头等舱',
    'F_S': '头等舱'
  }
  return labelMap[cabinClass] || cabinClass
}

const showTransferDetails = (flight) => {
  selectedTransferFlight.value = flight
  showTransferDialog.value = true
}

const viewFlightDetail = (flight) => {
  selectedFlight.value = flight
  showFlightDetailDialog.value = true
}

const handleExport = async (exportOptions) => {
  try {
    exporting.value = true

    const exportData = {
      searchRequest: { ...searchForm, tripType: 'oneway' },
      searchResponse: {
        ...searchResult,
        flights: exportOptions.selectedFlights || filteredFlights.value
      },
      exportOptions
    }

    await oneWayFlightApi.exportOneWayFlights(exportData)
    ElMessage.success('Excel文件已下载')
    showExportDialog.value = false
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败，请稍后重试')
  } finally {
    exporting.value = false
  }
}

const onTaskCreated = (task) => {
  ElMessage.success(`定时任务 "${task.name}" 创建成功`)
  showScheduleDialog.value = false
}

// 生命周期
onMounted(() => {
  const query = route.query
  if (query.departure) {
    Object.keys(query).forEach(key => {
      if (searchForm.hasOwnProperty(key)) {
        searchForm[key] = query[key]
      }
    })
  }
})
</script>

<style scoped>
.oneway-flight-search {
  max-width: 1400px;
  margin: 0 auto;
}

.search-card, .result-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 18px;
  font-weight: bold;
}

.result-summary {
  display: flex;
  gap: 10px;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.filter-controls {
  margin-bottom: 16px;
  padding: 12px;
  background-color: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e9ecef;
}

.control-group {
  display: flex;
  align-items: center;
  gap: 8px;
}

.control-label {
  font-size: 14px;
  color: #606266;
  white-space: nowrap;
}

.filter-stats {
  display: flex;
  gap: 8px;
  align-items: center;
}

.pagination-controls {
  margin: 16px 0;
  display: flex;
  justify-content: center;
}

.bottom-pagination {
  margin-top: 20px;
  padding-top: 16px;
  border-top: 1px solid #e4e7ed;
}

.flight-number-cell {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.flight-no {
  font-weight: bold;
  font-size: 14px;
}

.airline-info {
  font-size: 12px;
  color: #909399;
}

.flight-time {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.time-range {
  font-size: 13px;
  font-family: 'Courier New', monospace;
}

.duration {
  font-size: 12px;
  color: #909399;
}

.airport-info {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.airport-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 2px;
}

.city-name {
  font-size: 11px;
  color: #999;
}

.route-arrow {
  color: #409eff;
  flex-shrink: 0;
}

.price-cell {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 4px;
}

.price-display {
  display: flex;
  align-items: baseline;
  gap: 4px;
}

.currency {
  font-size: 12px;
  color: #909399;
}

.amount {
  font-size: 16px;
  font-weight: bold;
  color: #f56c6c;
}

.price-breakdown {
  font-size: 11px;
  color: #999;
  font-family: 'Courier New', monospace;
}

@media (max-width: 768px) {
  .oneway-flight-search {
    padding: 0 10px;
  }

  .filter-controls .el-row {
    flex-direction: column;
    gap: 12px;
  }

  .filter-controls .el-col {
    width: 100%;
  }

  .control-group {
    justify-content: space-between;
    width: 100%;
  }
}
</style>